//
//  MJTComposeViewController.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/18.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit
import SVProgressHUD
class MJTComposeViewController: UIViewController {
    //MARK: -- 懒加载控件
    private lazy var labelView: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 17)
        if let name = MJTUserAccountViewModel.shareUserAccount.userAccount?.name {
            let title = "发微博\n\(name)"
            //不为空设置富文本
            let attributedStr:NSMutableAttributedString = NSMutableAttributedString(string: title)
            //需要的副文本长度
            let range = (title as NSString).rangeOfString(name)
            //设置副文本
            attributedStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(),NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)

            label.attributedText = attributedStr
        } else {

            label.text = "发微博"
        }
        label.numberOfLines = 0
        label.textAlignment = .Center
        //自适应大小,尺寸设置才可以显示
        label.sizeToFit()
        return label
    }()
    //右侧点击按钮
    private lazy var rightButton: UIButton = {
        let button = UIButton()
        //添加点击事件
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)

        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        button.setTitle("发送", forState: .Normal)
        //设置文字属性
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        button.size = CGSize(width: 45, height: 30)
        //这里设置没用
        button.enabled = false
        return button
    }()
    private lazy var textView: MJTComposeTextView = {
        let view = MJTComposeTextView()
        //竖着方向可以拖拽
        view.alwaysBounceVertical = true
        view.font = UIFont.systemFontOfSize(14)
        view.delegate = self
        view.textColor = UIColor.grayColor()
        view.placeHolder = "听说👂下雨天☔️,音乐🎵和薯条🍟更配(⊙o⊙)哦..."
        
        return view
    }()
    // 配图
    private lazy var pictureView: MJTComposePictureView = {
        let view = MJTComposePictureView()
        return view
    }()
    //加载toolbar
    private lazy var toolbar: MJTComposeToolBar = {
        let tool = MJTComposeToolBar(frame: CGRectZero)
        return tool
    }()
    //表情键盘
    private lazy var emoticonKeyBoard: MJTEmoticonKeyBoard = {
        let view = MJTEmoticonKeyBoard()
        //size
        view.size = CGSize(width: self.textView.width, height: 216)
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()

        setupUI()
    }
    //MARK: -- 键盘改变的通知
    @objc private func keyboardChangeFrame(noti: NSNotification) {
        // 获取键盘的rect
        let keyboardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        toolbar.snp_updateConstraints { (make) -> Void in
            // 差一个键盘的高度
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - self.view.height)
        }
        let durationtime = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        UIView.animateWithDuration(durationtime) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    //  MARK:   -监听表情按钮点击
    @objc private func didSectedEmoticon(noti: NSNotification) {
//        let emoticon = noti.object as? MJTEmoticon
//        print(emoticon?.type)
        guard let emoticon = noti.object as? MJTEmoticon else {
            return
        }
        //封装出入表情分文本
        textView.insertEmoticon(emoticon, font: textView.font!)
//        //判断点击的表情类型
//        if emoticon.type == "0" {
////            textView.insertText(emoticon.chs!)
//            //记录上一次的副文本
//            let originalAttr = NSMutableAttributedString(attributedString: textView.attributedText)
//            // 1 ,根据表情图片路径名字创建一个UIImage
//            let image = UIImage(named: emoticon.path!)
//            //根据UIImage对象创建一个NSTextAttachment(文本附件)
//            let attachtment = NSTextAttachment()
//            attachtment.image = image
//            //取到字体高度
//            let fontHeight = textView.font!.lineHeight
//            attachtment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
//            //3,根据NSTextAttachment创建一个NSAttributedString (副文本)
//            let attr = NSAttributedString(attachment: attachtment)
//            //获取textView的选中范围
//            var range = textView.selectedRange
//            //替换选中的字符串
//            originalAttr.replaceCharactersInRange(range, withAttributedString: attr)
//            //追加副文本
//            originalAttr.appendAttributedString(attr)
//            //设置副文本的字体大小
//            originalAttr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, originalAttr.length))
//            //设置副文本
//            textView.attributedText = originalAttr
//            //每次点击表情开始位置加一
////            range.location += 1
//            //设置选中范围长度为0
//            range.length = 0
//            //设置选中范围
//            textView.selectedRange = range
//        } else {
//            textView.insertText((emoticon.code! as NSString).emoji())
//        }


    }
    //监听删除表情按钮点击的通知
    @objc private func didSelectedDeleteEmoticon() {
        //删除textView内容
        textView.deleteBackward()
    }
    private func setupUI() {
        setupNav()
        //  监听表情按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSectedEmoticon:", name: DidSeletedEmoticonNotification, object: nil)
        //监听键盘改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //监听删除表情按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedDeleteEmoticon", name: DidSelectedDeleteEmoticonButtonNotification, object: nil)
        view.addSubview(textView)
        view.addSubview(toolbar)
        textView.addSubview(pictureView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolbar.snp_top)
        }
        toolbar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(view)
            make.height.equalTo(35)
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(200)
            make.leading.equalTo(textView).offset(10)
            make.trailing.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        toolbar.selectedToolBarButtonClosure = { [weak self] (type: MJTComposeToolBarButtonType) in
            switch type {
            case .Picture:
                self?.didSelectPicture()
            case .Mention:
                print("点击了@按钮")
            case .Trend:
                print("点击了话题按钮")
            case .Emoticon:
//                print("点击了emoji按钮")
                self?.didSelectEmoticon()

            case .Add:
                print("点击了添加按钮")
            }

        }
        pictureView.selectedAddButtonClosure = { [weak self] in
            self?.didSelectPicture()

        }
    }
    private func setupNav() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "canculButton")
        self.navigationItem.titleView = labelView
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        self.navigationItem.rightBarButtonItem?.enabled = false

    }
    @objc private func canculButton() {
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @objc private func sendAction() {
        if pictureView.images.count > 0 {
            upload()
        } else {
            update()
        }
    }
    // MARK:    --发送带图片的微博
    private func upload() {

        //  发带有图片的微博
        let image = pictureView.images.first!
        let accesstoken = MJTUserAccountViewModel.shareUserAccount.accessToken!
        let status = textView.emticonText//textView.text!
        SVProgressHUD.show()
        MJTNetworkTools.sharedTools.upload(accesstoken, status: status, image: image, callBack: { (response, error) -> () in

            if error != nil {
                SVProgressHUD.dismiss()
                print(error)
                return
            }
            SVProgressHUD.showSuccessWithStatus("发布成功")
        })
        
    }
    private func update() {
        //  发送文字微博
        let accesstoken = MJTUserAccountViewModel.shareUserAccount.accessToken!
        let status = textView.emticonText//textView.text!
        SVProgressHUD.show()
        MJTNetworkTools.sharedTools.update(accesstoken, status: status) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.dismiss()
                print(error)
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
// -- toolbar按钮相关操作
extension MJTComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    // 点击表情按钮的逻辑处理
    func didSelectEmoticon() {
        // 如果是系统键盘让其进入表情键盘
        if textView.inputView == nil {
            textView.inputView = emoticonKeyBoard
            toolbar.showEmoticonIcon(true)
        } else {
            textView.inputView = nil
            toolbar.showEmoticonIcon(false)
        }
        //获取第一响应者
        textView.becomeFirstResponder()
        //重新加载自定义的inputView
        textView.reloadInputViews()
    }

    //MARK: 图片相关操作
    func didSelectPicture() {
        let pickerCtr = UIImagePickerController()
        //设置代理
        pickerCtr.delegate = self
        // 判断来源是否支持
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            print("支持相机")
            pickerCtr.sourceType = .Camera
        } else {
            print("不支持相机")
            pickerCtr.sourceType = .PhotoLibrary
        }
        //判断是否支持前置后置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("支持前置")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("支持后置")
        } else {
            print("前后都不支持")
        }
        presentViewController(pickerCtr, animated: true, completion: nil)

    }
//    //根据缩放后的宽度计算缩放后的高度
//    private func imageScaleForScaleWidth(width: CGFloat, image: UIImage) -> UIImage {
//        let height = width / image.size.width * image.size.height
//        let scaleSize = CGSize(width: width, height: height)
//        //开启上下文
//        UIGraphicsBeginImageContext(scaleSize)
//        image.drawInRect(CGRect(origin: CGPointZero, size: scaleSize))
//
//        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
//        //结束上下文
//        UIGraphicsEndImageContext()
//        return scaleImage
//
//    }
    //MARK: --
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //选中的图片
        let scaleImage = image.imageScaleForScaleWidth(200)
//        print(scaleImage)
        pictureView.addImage(scaleImage)
        // 图片选则完成,控制器销毁
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}
// MARK:    --UITextViewDelegate
extension MJTComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}